package com.yimi.yinhepda.views;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.AssetManager;
import android.content.res.TypedArray;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.view.WindowManager;

import com.baidu.mobstat.StatService;
import com.pda.uce.commom.util.LoadUtils;
import com.pda.ym.callbacks.UICallBack;
import com.pda.ym.entity.response.GetVersionResponse;
import com.pda.ym.net.NetRequest;
import com.pda.ym.utils.ActivityStack;
import com.pda.ym.utils.AppInfoHelper;
import com.pda.ym.utils.Constants;
import com.pda.ym.utils.FileUtil;
import com.yimi.yinhepda.BuildConfig;
import com.yimi.yinhepda.R;
import com.yimi.yinhepda.db.dao.DepartmentTableDao;
import com.yimi.yinhepda.db.dao.DepartmentTableTempDao;
import com.yimi.yinhepda.db.dao.LineVoTableDao;
import com.yimi.yinhepda.db.dao.LineVoTableTempDao;
import com.yimi.yinhepda.db.helper.DbHelper;
import com.yimi.yinhepda.db.helper.DbHelperTemp;
import com.yimi.yinhepda.db.helper.DbHelperUC;
import com.yimi.yinhepda.db.table.DepartmentTable;
import com.yimi.yinhepda.db.table.LineVoTable;
import com.yimi.yinhepda.entity.response.DeptInfoResponse;
import com.yimi.yinhepda.entity.response.SyncServerData;
import com.yimi.yinhepda.utils.Common;
import com.pda.ym.utils.DateHelper;
import com.yimi.yinhepda.utils.GzipUtil;
import com.pda.uce.commom.util.LogUtil;
import com.pda.uce.commom.util.MyDialog;
import com.yimi.yinhepda.utils.OkHttpDownUtil;
import com.yimi.yinhepda.utils.PermissionUtils;
import com.pda.ym.utils.SharedPreferUtil;
import com.yimi.yinhepda.utils.ToastUtil;
import com.yimi.yinhepda.utils.UtilDb;
import com.yimi.yinhepda.views.login.activity.LoginActivity;
import com.yimi.yinhepda.views.login.util.LoginUtil;

import java.io.File;
import java.lang.reflect.Method;
import java.sql.SQLException;
import java.text.DecimalFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * 欢迎界面
 *
 * @author 000432
 */
public class WelcomeActivity extends AppCompatActivity {

    protected MyDialog mPgDlg;
    private boolean isresult = false;
    private final int REQUEST_CODE_PERMISSIONS = 101;
    private String[] PERMISSIONS = new String[4];
    private long mPageSize = 1000;
    /**
     * 临时网点操作类
     */
    private DepartmentTableTempDao mTempDeptDao;
    /**
     * 正式网点操作类
     */
    private DepartmentTableDao mDeptDao;
    private LineVoTableTempDao mTempLineDao;
    private LineVoTableDao mLineDao;
    private DecimalFormat mDf;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 隐藏状态栏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.welcome);

        PERMISSIONS[0] = Manifest.permission.READ_PHONE_STATE;
        PERMISSIONS[1] = Manifest.permission.WRITE_EXTERNAL_STORAGE;
        PERMISSIONS[2] = Manifest.permission.CAMERA;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            PERMISSIONS[3] = Manifest.permission.READ_EXTERNAL_STORAGE;
        }

        mTempDeptDao = new DepartmentTableTempDao();
        mDeptDao = new DepartmentTableDao();
        mTempLineDao = new LineVoTableTempDao();
        mLineDao = new LineVoTableDao();

        mDf = new java.text.DecimalFormat("#");

        checkPersmisson();
    }

    @Override
    public void setRequestedOrientation(int requestedOrientation) {
        if (Build.VERSION.SDK_INT == Build.VERSION_CODES.O && isTranslucentOrFloating()) {
            LogUtil.e("avoid calling setRequestedOrientation when Oreo.");
            return;
        }
        super.setRequestedOrientation(requestedOrientation);
    }

    private boolean isTranslucentOrFloating() {
        boolean isTranslucentOrFloating = false;
        try {
            int[] styleableRes = (int[]) Class.forName("com.android.internal.R$styleable").getField("Window").get(null);
            final TypedArray ta = obtainStyledAttributes(styleableRes);
            Method m = ActivityInfo.class.getMethod("isTranslucentOrFloating", TypedArray.class);
            m.setAccessible(true);
            isTranslucentOrFloating = (boolean) m.invoke(null, ta);
            m.setAccessible(false);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return isTranslucentOrFloating;
    }

    private void checkPersmisson() {
        PermissionUtils.checkMorePermissions(this, PERMISSIONS, new PermissionUtils.PermissionCheckCallBack() {
            @Override
            public void onHasPermission() {
                //复制assets下的数据库文件 到指定位置
                downLoadZip();
            }

            @Override
            public void onUserHasAlreadyTurnedDown(String... permission) {
                PermissionUtils.requestMorePermissions(WelcomeActivity.this, PERMISSIONS, REQUEST_CODE_PERMISSIONS);
            }

            @Override
            public void onUserHasAlreadyTurnedDownAndDontAsk(String... permission) {
                PermissionUtils.requestMorePermissions(WelcomeActivity.this, PERMISSIONS, REQUEST_CODE_PERMISSIONS);
            }
        });
    }

    private void initView() {

        //校验设备型号
        if (android.os.Build.MODEL.equals(Common.DEV_MODEL)) {
            //横屏
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
        }
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                Intent intent = new Intent();
                intent.setClass(WelcomeActivity.this, LoginActivity.class);
                startActivity(intent);
                finish();
            }
        }, 2000);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case REQUEST_CODE_PERMISSIONS:
                PermissionUtils.onRequestMorePermissionsResult(WelcomeActivity.this, PERMISSIONS, new PermissionUtils.PermissionCheckCallBack() {
                    @Override
                    public void onHasPermission() {
                        //复制assets下的数据库文件 到指定位置
                        downLoadZip();
                    }

                    @Override
                    public void onUserHasAlreadyTurnedDown(String... permission) {
                        PermissionUtils.requestMorePermissions(WelcomeActivity.this, PERMISSIONS, REQUEST_CODE_PERMISSIONS);
                    }

                    @Override
                    public void onUserHasAlreadyTurnedDownAndDontAsk(String... permission) {
                        showPermissionDialog2("程序需要读取手机信息权限和文件读写权限，才能继续使用，请去权限界面打开！", REQUEST_CODE_PERMISSIONS);
                    }
                });
                break;
            default:
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case 100:
                isresult = true;
                break;
            case REQUEST_CODE_PERMISSIONS:
                checkPersmisson();
                break;
            default:
                break;
        }
    }

    protected void showPermissionDialog2(String msg, final int requestCode) {
        MyDialog dialog = new MyDialog(this);
        dialog.setIcon(R.drawable.alert);
        dialog.setDialogType(MyDialog.DialogType.ALERT_DIALOG);
        dialog.setTitle("提示");
        dialog.setMessage(msg);
        dialog.setPositiveClickListener("去打开", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                Uri packageURI = Uri.parse("package:" + getPackageName());
                Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, packageURI);
                startActivityForResult(intent, requestCode);
            }
        });
        dialog.setCanceledOnTouchOutside(false);
        dialog.setCancelable(false);
        dialog.show();
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (hasFocus && isresult) {
        }
    }

    public void showPgDlg(String msg) {
        if (this.isFinishing()) {
            return;
        }
        if (mPgDlg == null) {
            mPgDlg = new MyDialog(this);
            mPgDlg.setCancelable(false);
            mPgDlg.setCanceledOnTouchOutside(false);
            mPgDlg.setDialogType(MyDialog.DialogType.PROGRESS_DIALOG);
        }
        mPgDlg.setMessage(msg);
        if (!mPgDlg.isShowing()) {
            mPgDlg.show();
        }
    }

    public void dismissPgDlg() {
        try {
            if (mPgDlg != null) {
                mPgDlg.dismiss();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 下载解压db zip文件
     */
    private void downLoadZip() {
        final File dbDir = getExternalFilesDir(DbHelper.DB_FILE_DIR);
        if (dbDir == null) {
            initView();
            return;
        }
        File dbFile = new File(dbDir, DbHelper.TABLE_NAME);
        if (!dbFile.exists()) {
            queryDBInfo(dbDir.getPath(), Common.DB_ZIP_FILE, false);
        } else {
            boolean excuteTempDB = SharedPreferUtil.getInstance().getBooleanValue(Common.EXCUTE_TEMP_DB);
            if (BuildConfig.VERSION_CODE > 125 && !excuteTempDB) {
                queryDBInfo(dbDir.getPath(), Common.DB_ZIP_FILE, true);
            } else {
                initView();
            }
        }
    }

    /**
     * 查询db信息，获取下载url
     *
     * @param saveDir  zip保存目录
     * @param fileName zip文件名称
     */
    private void queryDBInfo(final String saveDir, final String fileName, final boolean isTempDB) {
        LoginUtil.queryDBInfo(this, saveDir, fileName, new UICallBack() {
            @Override
            public void onError(String msg) {
                retryDialog();
            }

            @Override
            public void onSuccess(Object obj) {
                unCompressZip(saveDir, fileName, isTempDB);
            }
        });
    }

    /**
     * 解压下载的zip文件
     *
     * @param saveDir  解压目录
     * @param fileName zip文件名称
     * @param isTempDB 覆盖安装时，下载数据库至临时目录，copy网点表和线路表中的数据至正式表中
     */
    private void unCompressZip(final String saveDir, final String fileName, final boolean isTempDB) {
        new Handler(Looper.getMainLooper()).post(new Runnable() {
            @Override
            public void run() {
                LoadUtils.showLoading("解压中...", WelcomeActivity.this);
            }
        });

        Observable.create(new Observable.OnSubscribe<Void>() {
            @Override
            public void call(Subscriber<? super Void> subscriber) {
                String zipFilePath = saveDir + "/" + fileName;
                if (!isTempDB) {
                    //解压正式db文件
                    GzipUtil.uncompressZip4j(zipFilePath, saveDir, DbHelper.TABLE_NAME, Common.ZIP_PWD);
                } else {
                    File tempDBDir = getExternalFilesDir(DbHelperTemp.DB_FILE_DIR);
                    //解压临时db文件
                    GzipUtil.uncompressZip4j(zipFilePath, tempDBDir.getPath(), DbHelperTemp.TABLE_NAME, Common.ZIP_PWD);

                    //清除正式网点表中的数据，将temp中的网点表数据copy至正式网点表中
                    mDeptDao.deleteAll();
                    insertDepartTableData(0, mPageSize, mTempDeptDao.findTotalSize());

                    //清除正式线路表，将temp中的线路表copy至正式线路表中
                    mLineDao.deleteAll();
                    long totalSize = mTempLineDao.findTotalSize(DateHelper.getDateTimeFormate(new Date()));
                    insertLineTableData(0, mPageSize, DateHelper.getDateTimeFormate(new Date()), totalSize);

                    SharedPreferUtil.getInstance().setBooleanValue(Common.EXCUTE_TEMP_DB, true);

                    //删除tempdb文件
                    deleteTempDB();
                }


                subscriber.onCompleted();
            }
        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<Void>() {
            @Override
            public void onCompleted() {
                LoadUtils.hideLoading(WelcomeActivity.this);
                LogUtil.e("下载解压DB文件结束--->" + DateHelper.getDateTimeFormate(new Date()));
                if (!isTempDB) {
                    //设置初始环境IP，用于登录后不再全量更新数据库(首次安装)
                    SharedPreferUtil.getInstance().setValue(Common.OLD_SERVER, SharedPreferUtil.getInstance().getServerIp());
                    SharedPreferUtil.getInstance().setBooleanValue(Constants.FISRT_COPY_DB_FILE, true);
                    SharedPreferUtil.getInstance().setBooleanValue(Common.EXCUTE_TEMP_DB, true);
                }
                initView();

            }

            @Override
            public void onError(Throwable throwable) {
                LoadUtils.hideLoading(WelcomeActivity.this);
                ToastUtil.showToast("解压失败！");
                retryDialog();
            }

            @Override
            public void onNext(Void aVoid) {
            }
        });
    }

    private void retryDialog() {
        LoginUtil.retryDialog(this,new DialogInterface.OnClickListener(){

            @Override
            public void onClick(DialogInterface dialog, int which) {
                downLoadZip();
            }
        });
    }

    /**
     * 删除TempDB文件
     */
    private void deleteTempDB() {
        File dirFile = getExternalFilesDir(DbHelperTemp.DB_FILE_DIR);
        for (File file : dirFile.listFiles()) {
            file.delete();
        }
    }

    /**
     * 分页查询插入网点数据
     *
     * @param currentPage 当前页
     * @param pageSiz     每页大小
     */
    private void insertDepartTableData(final long currentPage, final long pageSiz, final long totalSize) {
        try {
            List<DepartmentTable> tempData = mTempDeptDao.findDataByPage(currentPage, pageSiz);
            if (tempData == null || tempData.isEmpty()) {
                return;
            }
            mDeptDao.insert(tempData);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        LogUtil.e("网点表插入：currentPage=" + currentPage);
        new Handler(Looper.getMainLooper()).post(new Runnable() {
            @Override
            public void run() {
                if (currentPage * pageSiz <= totalSize) {
                    LoadUtils.showLoading("更新网点资料中..." + mDf.format(((float) (currentPage * pageSiz) / totalSize) * 100) + "/100%(1/2)", WelcomeActivity.this);
                }
            }
        });
        insertDepartTableData(currentPage + 1, pageSiz, totalSize);
    }

    /**
     * 分页查询插入线路数据
     *
     * @param currentPage 当前页
     * @param pageSiz     每页大小
     */
    private void insertLineTableData(final long currentPage, final long pageSiz, String currentDate, final long totalSize) {
        try {
            List<LineVoTable> tempData = mTempLineDao.findDataByPage(currentPage, pageSiz, currentDate);
            if (tempData == null || tempData.isEmpty()) {
                return;
            }
            mLineDao.insert(tempData);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        LogUtil.e("线路表插入：currentPage=" + currentPage);
        new Handler(Looper.getMainLooper()).post(new Runnable() {
            @Override
            public void run() {
                if (currentPage * pageSiz <= totalSize) {
                    LoadUtils.showLoading("更新线路资料中..." + mDf.format(((float) (currentPage * pageSiz) / totalSize) * 100) + "/100%(2/2)", WelcomeActivity.this);
                }
            }
        });
        insertLineTableData(currentPage + 1, pageSiz, currentDate, totalSize);
    }
}
